<script setup lang="ts">
import { useInjectDisabled } from 'ant-design-vue/es/config-provider/DisabledContext';
import { Captcha } from '~/components/captcha';

const props = withDefaults(defineProps<{
  disabled?: boolean | undefined;
}>(), {
  disabled: undefined,
});

const value = defineModel<string>('value', { default: '' });
const captchaId = defineModel<string>('captchaId', { default: '' });
const $captcha = ref();
const antdDisabled = useInjectDisabled();
const disabled = computed(() => props.disabled ?? antdDisabled.value ?? false);

function onChange(data: VueEmitParam<typeof Captcha, 'change'>) {
  captchaId.value = data?.id ?? '';
  // captchaId 变化时清空 value 值（特殊操作是为了避免再次刷新验证码）
  value.value = ' ';
  nextTick(() => value.value = '');
}

watch(value, (newVal = '', oldVal = '') => {
  // 当清空值时刷新验证码
  const refreshable = newVal.length === 0 && (oldVal.length - newVal.length > 1);
  refreshable && $captcha.value?.refresh();
});
</script>

<template>
  <div class="flex">
    <AInput
      v-model:value="value"
      class="mr-3 flex-1" :disabled="disabled" inputmode="numeric"
      :placeholder="$t('dm31Qszs43DryDzTcFm')"
      :maxlength="5"
    >
      <template #prefix>
        <i class="i-ri:shield-keyhole-fill mr-1 text-1.2em text-sys-text-body" />
      </template>
    </AInput>
    <Captcha
      ref="$captcha" :disabled="disabled"
      @change="onChange"
    />
  </div>
</template>
